#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;

const ll N = 2e5 + 10, INF = 0x3f3f3f3f;

ll n, m;
set<ll> g[N];
vector<pair<ll, ll>> li[N];
set<ll> s[N];
ll f[N];

void solve()
{
    cin >> n >> m;
    for (ll i = 1;i <= m;i++) {
        ll a, b, c;cin >> a >> b >> c;
        g[b].insert(a); g[c].insert(a);
        li[a].push_back({ b,c });
        s[a].insert(b);s[a].insert(c);
    }

    queue<ll> q;
    ll ans = 0, cnt = 0;
    for (ll i = 1;i <= n;i++) if (s[i].size() == 0) { q.push(i), f[i] = 1; }

    while (!q.empty()) {
        ll x = q.front();q.pop();
        cnt++;
        for (auto& [p, q] : li[x]) f[x] = max(f[x], f[p] + f[q]);
        ans += f[x];
        if (ans > 1e9) { cout << -1 << '\n'; return; }
        for (ll y : g[x]) {
            s[y].erase(x);
            if (s[y].size() == 0) q.push(y);
        }
    }

    if (cnt != n)  cout << -1 << '\n';
    else  cout << ans << '\n';
}

signed main()
{
    //ios::sync_with_stdio(0);
    //cin.tie(0);cout.tie(0);
#define ONLINE_JUDGE
#ifndef ONLINE_JUDGE
    std::istringstream in(R"()");
    std::cin.rdbuf(in.rdbuf());
#endif
    ll T = 1;
    //cin>>T;
    for (ll i = 1;i <= T;i++) {
        solve();
    }
}